/*
 * @lc app=leetcode.cn id=110 lang=javascript
 *
 * [110] 平衡二叉树
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {boolean}
 */
var getHeight = function (root) {
  if (!root) return 0;
  let left = getHeight(root.left);
  let right = getHeight(root.right);
  // 此根节点失衡
  if (Math.abs(left - right) > 1) return -2;
  // 左子树或右子树失衡
  if (left < 0 || right < 0) return -2;
  return Math.max(left, right) + 1;
}
var isBalanced = function (root) {
  return getHeight(root) >= 0;
};


/**
 * 复习 2021-08-04
 */

var getHeight = function (root) {
  if (!root) return 0;
  let left = getHeight(root.left) + 1;
  let right = getHeight(root.right) + 1;
  return Math.max(left, right);
}
var isBalanced = function (root) {
  if (!root) return true;
  let left = getHeight(root.left);
  let right = getHeight(root.right);

  if (Math.abs(left - right) > 1) return false;
  if (!isBalanced(root.left) || !isBalanced(root.right)) {
    return false;
  };
  return true;
}
// @lc code=end

